from home.models import *
from django.conf import settings
import os
import pandas as pd
import sys
import traceback
import argparse

def replace_substring(filePath,name,newName):
    #filePath:文件路径
    #name:要替换的字符串
    #newName:替换后的字符串
    #返回新的文件路径
    #如果文件路径中不存在name，则返回原文件路径
    if name in filePath:
        return filePath.replace(name, newName)
    else:
        return filePath
def renameFile(path,filePath,name,newName):
    try:
        print(path, filePath,name,newName)
        if os.path.exists(os.path.join(path,filePath)):
            print("path exists")
            print("rename now!")
            newFilePath=replace_substring(filePath, name, newName)
            #将filePath中的name替换为newName
            #找到filePath中的字符串与name变量相同的部分，并把它替换成newName变量的内容


            print("newFilePath:", os.path.join(path, newFilePath))
            os.rename(os.path.join(path, filePath), os.path.join(path, newFilePath))
            print("rename done!")
            return {"name":newName,"path":newFilePath}
        else:
            print("path not exists")
            return False
    except:
        print("rename error")
        return False

def updateFile(path, filePath, name, content):
    try:
        print(path, filePath, name, content)
        if os.path.exists(os.path.join(path, filePath)):
            print("path exists")
            print("update now!")
            print("updatePath:", os.path.join(path, filePath))
            with open(os.path.join(path, filePath), "w", encoding="utf-8") as f:
                f.write(content)
            print("update done!")
            return True
        else:
            print("path not exists")
            return False
    except:
        print("update error")
        return False
def moveFile(path, filePath,name,newPath):
    try:
        print(path, filePath, newPath)
        if os.path.exists(os.path.join(path, filePath)):
            print("path exists")
            if os.path.exists(os.path.join(path, newPath))==False:
                os.mkdir(os.path.join(path, newPath))
            #判断文件是否重复，如果重复，就建一个新名字
            newfilePath=checkPath(os.path.join(path, newPath), name, "file")
            print("move now!")
            print("movePath:", os.path.join(path, filePath))
            print("newPath:", os.path.join(path, newPath,newfilePath))
            os.rename(os.path.join(path, filePath), os.path.join(path, newPath,newfilePath))
            print("move done!")
            return True
        else:
            print("path not exists")
            return False
    except:
        print("move error")
        return False
def deleteFile(path,filePath,name):
    try:
        print(path, filePath, name)
        if os.path.exists(os.path.join(path, filePath)):
            print("path exists")
            print("delete now!")
            print("deletePath:", os.path.join(path, filePath))
            #将文件移至回收站
            moveFile(path, filePath,name,"recycle")
            #os.remove(os.path.join(path, filePath))
            print("delete done!")
            return True
        else:
            print("path not exists")
            return False
    except:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        # 输出所有的异常信息
        print("发生异常：")
        print("异常类型:", exc_type)
        print("异常值:", exc_value)
        print("追踪信息:")
        traceback.print_tb(exc_traceback)
        return False
def checkPath(tempPath,name,type="dir"):
    print("checkPath")
    inputName=name
    tempIndex=1
    while os.path.exists(os.path.join(tempPath,name)):
        print("newPath:",os.path.join(tempPath,name))
        #tempCount+=1
        print("存在")
        #如果指明了要添加的是md文件，那么就添加
        if type!="dir":
            tempName=inputName.rsplit('.',1)
            namebody=tempName[0]
            nametype=tempName[1]
            name = namebody + '(' + str(tempIndex) + ')'+'.'+nametype
        else:
            name = inputName + '(' + str(tempIndex) + ')'
        tempIndex+=1
        print("name:",name,"tempIndex:",tempIndex)
    return name
def addFolder(path,filePath,name,folder_type):
    try:
        print(path,filePath,name)
        if os.path.exists(path):
            print("path exists")
            #判断os.path.join(path, name)是否存在，不存在则创建，存在则在地址后面加上(1)
            
            #tempCount=0
            if filePath:
                tempPath=os.path.join(path, filePath)
            else:
                tempPath=path
            #目录如果类型不是md，那么就自动归为dir
            if folder_type!="md":
                folder_type="dir"
            else:
                name=name+".md"
            name=checkPath(tempPath,name,type=folder_type)
            print("mkdir now!")
            print("newPath:",os.path.join(tempPath, name))
            #如果指明了要添加的是md文件，那么就添加
            if folder_type=="md":
                with open(os.path.join(tempPath, name), 'w') as file:
                    file.write("# "+name)
            else:
                os.mkdir(os.path.join(tempPath,name))
            print("mkdir done!")
            if filePath:
                return {"name":name,"path":os.path.join(filePath, name)}
            else:
                return {"name":name,"path":name}
        else:
            print("path not exists")
            return False
    except:
        print("mkdir error")
        return False
def get_file_type(file_path):
    filename = file_path.split('/')[-1]  # 获取文件名
    extension = filename.split('.')[-1]  # 获取文件后缀

    file_type = ''

    if extension.lower() in ['jpg', 'png', 'gif','jpeg']:
        file_type = 'image'
    elif extension.lower() == 'pdf':
        file_type = 'pdf'
    elif extension.lower() in ['doc', 'docx']:
        file_type = 'doc'
    elif extension.lower() in ['xls', 'xlsx']:
        file_type = 'xls'
    elif extension.lower() in ['txt']:
        file_type = 'text'
    elif extension.lower() in ['md']:
        file_type = 'md'
    elif extension.lower() in ['py']:
        file_type = 'python'
    elif extension.lower() in ['mp3', 'wav', 'flac']:
        file_type = 'audio'
    elif extension.lower() in ['mp4', 'avi', 'mkv']:
        file_type = 'video'
    elif extension.lower() in ['epub']:
        file_type = 'ebook'
    else:
        file_type = 'unknown'

    return {'path': file_path, 'type': file_type}

def generate_znodes(path):
    znodes = []
    parent_ids = {path: 0}
    current_id = 1

    queue = [path]
    while queue:
        current_path = queue.pop(0)
        current_parent_id = parent_ids[current_path]

        for item in os.listdir(current_path):
            item_path = os.path.join(current_path, item)

            if os.path.isdir(item_path):
                znodes.append({
                    'id': current_id,
                    'pId': current_parent_id,
                    'name': item,
                    'path': os.path.relpath(item_path, path),
                    'type':'dir',
                    'isParent':1
                })

                parent_ids[item_path] = current_id
                current_id += 1
                queue.append(item_path)
            elif os.path.isfile(item_path):
                getType=get_file_type(item_path)['type']
                znodes.append({
                    'id': current_id,
                    'pId': current_parent_id,
                    'name': item,
                    'path': os.path.relpath(item_path, path),
                    'type':getType

                })
                current_id += 1

    return znodes
def getStandard():
    # 指定静态文件相对路径
    file_path = 'data/'

    # 获取静态文件根目录的路径
    static_root = settings.STATIC_ROOT
    # 拼接文件完整路径
    full_path = os.path.join(static_root, file_path)

    if os.path.exists(full_path):
        print("路径存在")
    else:
        print("路径不存在")
    # 获取完整路径下的文件名
    #file_names = os.listdir(full_path)

    # 将文件名转化成一个列表
    #file_list = list(file_names)

    #print(file_list)
    #return file_list
    result = {}
    #print("full_path:", full_path)
    for root, dirs, files in os.walk(full_path):
        files_list = [f for f in files if os.path.isfile(os.path.join(root, f))]
        dirs_list = [d for d in dirs if os.path.isdir(os.path.join(root, d))]
        folder_name = os.path.basename(root)  # 获取当前文件夹的名称
        if folder_name=="":
            folder_name="root"
        result[folder_name] = {"files": files_list, "folders": dirs_list}
    #print("result:",result)
    return result
    

def readStandard(reauest,wordsType,wordsName):
    # 读取 Excel 文件
    # 指定静态文件相对路径
    file_path = 'data/standard/'+wordsType+'/'
    # 获取静态文件根目录的路径
    static_root = settings.STATIC_ROOT
    # 拼接文件完整路径
    full_path = os.path.join(static_root, file_path)
    if os.path.exists(full_path):
        print("路径存在")
    else:
        print("路径不存在")
    wordsName+='.xlsx'
    print("wordsName",wordsName)
    df = pd.read_excel(os.path.join(full_path, wordsName))
    # 提取第一列和第二列的数据，并将其转化为列表形式
    data = df.iloc[:, 0:2].values.tolist()

    # 构建目标列表
    
    result = [{"name": row[0], "desc": row[1] if len(row) > 1 else ""} for row in data]

    # 打印结果列表
    for item in result:
        print(item)
    return result

def checkPlatform():

    if sys.platform.startswith('win'):
        print("当前操作系统是 Windows")
        return 'W'
    elif sys.platform.startswith('linux'):
        print("当前操作系统是 Linux")
        return 'L'
    elif sys.platform.startswith('darwin'):
        print("当前操作系统是 macOS")
        return 'M'
    else:
        print("无法确定当前操作系统")
        return 'O'
    